package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileManagerApi;
import com.xuecheng.common.util.RandomStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileController implements FileManagerApi {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${file.service.url}")
    private String fileServiceUrl;
    @Value("${file.service.bucket}")
    private String bucketName;
    @Value("${file.service.upload.region}")
    private String uploadRegion;
    @Value("${cdn.domain}")
    private String domain;

    //客户端获取文件上传凭证
    @GetMapping("common/qnUploadToken")
    public Map<String, Object> generateUploadToken() {

        HashMap<String, Object> params = new HashMap<>();
        params.put("tokenType", "1");
        params.put("scope", "xc-public-images");
        params.put("deadline", 3600);
        params.put("key", UUID.randomUUID().toString() + "_" + RandomStringUtil.getRandomString(32));

        ResponseEntity<Map> response = this.restTemplate.postForEntity(fileServiceUrl, params, Map.class);
        //返回的结果map对象
        Map body = response.getBody();
        //获取凭证内容
        Object qnToken = body.get("result");
        //设置凭证内容
        params.put("qnToken", qnToken);
        //设置cdn域名
        params.put("domain", domain);
        //设置存储的片区(如上海=>华东)
        params.put("up_region", uploadRegion);
        return params;
    }
}
